﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;


namespace LiveProjectManager.DDD.Services
{
    public class ConfigService : Base.Service<Domains.Config>
    {
        public ConfigService() : base()
        {
        }


        override public ICollection<Domains.Config> getAll(int paginateBy = 0, int page = 1)
        {
            if (paginateBy > 0)
            {
                if (page <= 0)
                    page = 1;
                return (from f in _repository orderby f.Id select f).Skip(paginateBy * (page - 1)).Take(paginateBy).ToList();
            }
            return (from f in _repository orderby f.Id select f).ToList();
        }


        override public Domains.Config getById(long myId)
        {
            ICollection<Domains.Config> myResults = (from c in _repository where c.Id == myId select c).ToList();
            return (myResults.Count != 1) ? null : myResults.First();
        }


        public Domains.Config getByKey(string myKey)
        {
            ICollection<Domains.Config> myResults = (from c in _repository where c.Key == myKey select c).ToList();
            return (myResults.Count != 1) ? null : myResults.First();
        }


        public bool exists(string myKey)
        {
            return (getByKey(myKey) != null);
        }


        public bool create(
            string myKey,
            string myValue,
            bool autoSave = true
        )
        {
            // User already exists.
            if (exists(myKey))
                return false;

            // Create the new user.
            Domains.Config myNewConfig = new Domains.Config()
            {
                Key = myKey,
                Value = myValue
            };

            // Insert in repository.
            _repository.Add(myNewConfig);
            if (autoSave)
                _context.SaveChanges();
            return true;
        }


        override public bool remove(long myId, bool autoSave = true)
        {
            Domains.Config myConfig = getById(myId);
            if (myConfig == null)
                return false;
            _repository.Remove(myConfig);
            if (autoSave)
                _context.SaveChanges();
            return true;
        }
    }
}